<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT控制客户端</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
        .btn { padding: 10px 20px; margin: 5px; cursor: pointer; }
        .log { height: 200px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; }
        .subscription { display: inline-block; margin: 5px; padding: 5px 10px; background: #e0e0e0; border-radius: 3px; }
        .subscription button { margin-left: 10px; padding: 2px 8px; background: #ff4444; color: white; border: none; border-radius: 2px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>MQTT控制客户端</h1>
    
    <div class="section">
        <h3>连接状态</h3>
        <div id="status">未连接</div>
        <button class="btn" onclick="connectMQTT()">连接</button>
        <button class="btn" onclick="disconnectMQTT()">断开</button>
    </div>

    <div class="section">
        <h3>订阅主题</h3>
        <input type="text" id="subscribeTopic" placeholder="输入要订阅的主题" value="display/status">
        <button class="btn" onclick="subscribeTopic()">订阅</button>
        <button class="btn" onclick="unsubscribeAll()">取消所有订阅</button>
        <div id="subscriptions"></div>
    </div>

    <div class="section">
        <h3>发送消息</h3>
        <select id="messageType">
            <option value="text">文本</option>
            <option value="image">图片</option>
            <option value="video">视频</option>
            <option value="webpage">网页</option>
            <option value="clear">清除</option>
        </select>
        <input type="text" id="messageContent" placeholder="内容或URL">
        <input type="number" id="duration" placeholder="时长(毫秒)" value="0">
        <button class="btn" onclick="sendMessage()">发送</button>
    </div>

    <div class="section">
        <h3>预设消息</h3>
        <button class="btn" onclick="sendPreset('welcome')">欢迎信息</button>
        <button class="btn" onclick="sendPreset('image')">测试图片</button>
        <button class="btn" onclick="sendPreset('video')">测试视频</button>
        <button class="btn" onclick="sendPreset('clear')">清除</button>
    </div>

    <div class="section">
        <h3>日志</h3>
        <div id="log" class="log"></div>
    </div>

    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <script>
        let mqttClient = null;
        let isConnected = false;
        let deviceId = null;
        let targetTopic = 'display/control';
        let subscribedTopics = new Set();

        // 初始化设备配置
        function initDeviceConfig() {
            const urlParams = new URLSearchParams(window.location.search);
            deviceId = urlParams.get('deviceid');
            
            if (deviceId) {
                targetTopic = `display/control/${deviceId}`;
                console.log('检测到设备ID:', deviceId);
                console.log('目标主题:', targetTopic);
                
                // 更新页面显示
                const status = document.getElementById('status');
                status.textContent = `未连接 (设备ID: ${deviceId})`;
            } else {
                console.log('未检测到设备ID，使用默认主题:', targetTopic);
            }
        }

        // 页面加载时初始化
        initDeviceConfig();

        function connectMQTT() {
            if (isConnected) return;
            
            mqttClient = mqtt.connect('wss://broker.emqx.io:8084/mqtt', {
                clientId: 'control_' + Math.random().toString(16).substr(2, 8)
            });

            mqttClient.on('connect', () => {
                isConnected = true;
                const statusText = deviceId ? `已连接 (设备ID: ${deviceId})` : '已连接';
                document.getElementById('status').textContent = statusText;
                addLog('连接成功');
                addLog('目标主题: ' + targetTopic);
                
                // 重新订阅之前的主题
                subscribedTopics.forEach(topic => {
                    subscribeToTopic(topic);
                });
            });

            mqttClient.on('message', (topic, message) => {
                addLog(`收到消息 [${topic}]: ${message.toString()}`);
            });

            mqttClient.on('error', (err) => {
                addLog('错误: ' + err.message);
            });
        }

        function disconnectMQTT() {
            if (mqttClient) {
                mqttClient.end();
                mqttClient = null;
            }
            isConnected = false;
            const statusText = deviceId ? `未连接 (设备ID: ${deviceId})` : '未连接';
            document.getElementById('status').textContent = statusText;
        }

        function subscribeTopic() {
            const topic = document.getElementById('subscribeTopic').value.trim();
            if (!topic) {
                addLog('请输入要订阅的主题');
                return;
            }
            
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }
            
            if (subscribedTopics.has(topic)) {
                addLog('已经订阅了该主题: ' + topic);
                return;
            }
            
            subscribeToTopic(topic);
        }

        function subscribeToTopic(topic) {
            mqttClient.subscribe(topic, (err) => {
                if (err) {
                    addLog('订阅失败: ' + err.message);
                } else {
                    subscribedTopics.add(topic);
                    addLog('订阅成功: ' + topic);
                    updateSubscriptionsDisplay();
                }
            });
        }

        function unsubscribeTopic(topic) {
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }
            
            mqttClient.unsubscribe(topic, (err) => {
                if (err) {
                    addLog('取消订阅失败: ' + err.message);
                } else {
                    subscribedTopics.delete(topic);
                    addLog('取消订阅: ' + topic);
                    updateSubscriptionsDisplay();
                }
            });
        }

        function unsubscribeAll() {
            if (!isConnected) {
                addLog('请先连接MQTT');
                return;
            }
            
            subscribedTopics.forEach(topic => {
                mqttClient.unsubscribe(topic, (err) => {
                    if (err) {
                        addLog('取消订阅失败: ' + err.message);
                    } else {
                        addLog('取消订阅: ' + topic);
                    }
                });
            });
            
            subscribedTopics.clear();
            updateSubscriptionsDisplay();
        }

        function updateSubscriptionsDisplay() {
            const container = document.getElementById('subscriptions');
            container.innerHTML = '';
            
            subscribedTopics.forEach(topic => {
                const div = document.createElement('div');
                div.className = 'subscription';
                div.innerHTML = `
                    <span>${topic}</span>
                    <button onclick="unsubscribeTopic('${topic}')">取消</button>
                `;
                container.appendChild(div);
            });
        }

        function sendMessage() {
            if (!isConnected) {
                addLog('请先连接');
                return;
            }

            const type = document.getElementById('messageType').value;
            const content = document.getElementById('messageContent').value;
            const duration = parseInt(document.getElementById('duration').value) || 0;

            const message = { type };
            
            if (type === 'text') {
                message.content = content;
            } else if (type !== 'clear') {
                message.url = content;
            }
            
            if (duration > 0) message.duration = duration;
            if (type === 'video') {
                message.autoplay = true;
                message.muted = true;
            }

            publishMessage(message);
        }

        function sendPreset(type) {
            const presets = {
                welcome: { type: 'text', content: '欢迎使用远程控制显示系统！', duration: 5000 },
                image: { type: 'image', url: 'https://picsum.photos/1920/1080', duration: 8000 },
                video: { type: 'video', url: 'https://sample-videos.com/video321/mp4/720/big_buck_bunny_720p_1mb.mp4', autoplay: true, muted: true, duration: 15000 },
                clear: { type: 'clear' }
            };

            if (presets[type]) {
                publishMessage(presets[type]);
            }
        }

        function publishMessage(message) {
            mqttClient.publish(targetTopic, JSON.stringify(message), (err) => {
                if (err) {
                    addLog('发送失败: ' + err.message);
                } else {
                    addLog('发送到主题 ' + targetTopic + ': ' + JSON.stringify(message));
                }
            });
        }

        function addLog(message) {
            const log = document.getElementById('log');
            log.innerHTML += '<div>' + new Date().toLocaleTimeString() + ': ' + message + '</div>';
            log.scrollTop = log.scrollHeight;
        }
    </script>
</body>
</html> 